import { Form, Upload, message, Button } from 'antd';
import { UploadOutlined, PlusOutlined } from '@ant-design/icons';
import React from 'react'
import { ossData } from '@/services/file/api'
import styles from './index.less';
import { PageContainer } from '@ant-design/pro-layout'



class AliyunOSSUpload extends React.Component {
  state = {
    loading: false,
    OSSData: {},
  };

  async componentDidMount() {
    await this.init();
  }

  init = async () => {
    try {
      const OSSData = await this.mockGetOSSData();
      console.log(OSSData)
      this.setState({
        imageUrl: '',
        loading: false,
        OSSData,
      });
    } catch (error) {
      message.error(error);
    }
  };

  // Mock get OSS api
  // https://help.aliyun.com/document_detail/31988.html
  mockGetOSSData = async () => {
    const { data } = await ossData()
    return data
  };

  onChange = ({ fileList }) => {
    const { onChange } = this.props;
    console.log('Aliyun OSS:', fileList);
    if (onChange) {
      onChange([...fileList]);
    }
  };

  onRemove = file => {
    const { value, onChange } = this.props;

    const files = value.filter(v => v.url !== file.url);

    if (onChange) {
      onChange(files);
    }
  };

  getExtraData = file => {
    const { OSSData } = this.state;

    return {
      key: file.url,
      OSSAccessKeyId: OSSData.accessId,
      policy: OSSData.policy,
      Signature: OSSData.signature,
    };
  };

  beforeUpload = async file => {
    const { OSSData } = this.state;
    const expire = OSSData.expire * 1000;

    if (expire < Date.now()) {
      await this.init();
    }

    const suffix = file.name.slice(file.name.lastIndexOf('.'));
    const filename = Date.now() + suffix;
    file.url = OSSData.dir + filename;

    return file;
  };

  render() {
    const { value } = this.props;
    const { loading, imageUrl } = this.state;
    const props = {
      listType: "picture-card",
      name: 'file',
      fileList: value,
      action: this.state.OSSData.host,
      onChange: this.onChange,
      onRemove: this.onRemove,
      data: this.getExtraData,
      beforeUpload: this.beforeUpload,
    };

    const uploadButton = (
      <div>
        {loading ? <LoadingOutlined /> : <PlusOutlined />}
        <div style={{ marginTop: 8 }}>Upload</div>
      </div>
    );

    return (
      <Upload {...props}>
        {/* {imageUrl != '' ? <img src={imageUrl} alt="avatar" style={{ width: '100%' }} /> : uploadButton} */}
        {value.length >= 1 ? null : uploadButton}
        {/* <Button icon={<UploadOutlined />}>Click to Upload</Button> */}
      </Upload>
    );
  }
}

const FormPage = () => (
  <PageContainer>
    <div style={{ backgroundColor: 'white' }}>
      <Form labelCol={{ span: 4 }}>
        <Form.Item label="Photos" name="photos">
          <AliyunOSSUpload />
        </Form.Item>
      </Form>
    </div>

  </PageContainer>
);

export default FormPage
